package cn.k7g.alloy.core.objectmapper;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.reflect.MethodUtils;

import java.io.IOException;

/**
 * 序列化枚举类型
 * @date  2022/1/19 上午10:59
 * @author victor-wu
 */

public class EnumSerializer extends JsonSerializer<Enum> {
    @Override
    public void serialize(Enum v, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (v == null) {
            jsonGenerator.writeNull();
            return;
        }
        jsonGenerator.writeString(v.name());
        String label = v.name();
        try {
            label = (String) MethodUtils.invokeMethod(v, "getLabel");
        } catch (Exception e) { }
        String currentName = jsonGenerator.getOutputContext().getCurrentName();
        if (currentName != null) {
            jsonGenerator.writeStringField(currentName + "Label", label);
        }
    }
}
